package controller;

import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.AuthorModel;
import model.QuestionModel;
import entity.Author;
import entity.Question;

/**
 * Servlet implementation class AuthorAnswer
 */
@WebServlet("/AuthorAnswer")
public class AuthorAnswer extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// Language
		HttpSession session = request.getSession(true);
		ResourceBundle resource = null;
		String lang = "";
		if (session.getAttribute("language") != null) {
			resource = (ResourceBundle) session.getAttribute("language");
			lang = resource.getString("code");

		} else {
			resource = ResourceBundle.getBundle("en", new Locale("en"));
			session.setAttribute("language", resource);
			lang = "en";
		}

		// Get author alias from uri
		String path = ((HttpServletRequest) request).getRequestURI();
		String[] splittedURI = path.split("/");
		String alias = splittedURI[3];

		// Paginate
		int currentPage = 0;		
		if (splittedURI.length == 5) {
			currentPage = Integer.valueOf(splittedURI[4]);
		}
		
		// Property handle
		request.setAttribute("title", resource.getString("title"));
		request.setAttribute("keyword", resource.getString("keyword"));
		request.setAttribute("description", resource.getString("description"));

		// Return view
		QuestionModel questionModel = new QuestionModel();
		AuthorModel authorModel = new AuthorModel();
		List<Question> listAnswer = questionModel.findByAnswer(alias, lang, currentPage);
		Author author = authorModel.findByAlias(alias);
		if (listAnswer.size()<=0) {
			currentPage = 0;
			listAnswer = questionModel.findByAnswer(alias, lang, currentPage);
		}
		
		request.setAttribute("currentPage", currentPage);
		request.setAttribute("listAnswer", listAnswer);
		request.setAttribute("author", author);
		request.getRequestDispatcher("/author_answer.jsp").forward(request,
				response);
	}

}
